/**
 * Created by xie on 2018/3/13.
 */
angular.module('module.personalcenter')
    .controller('LikeController', LikeController);

LikeController.$inject = ['$scope', '$state', '$cookieStore', '$rootScope', 'AutherService', '$cookies'];

function LikeController($scope, $state, $cookieStore, $rootScope, AutherService, $cookies) {
    var vm = this;
    vm.addlabel = addlabel;
    vm.save = save;
    vm.selectlabel = selectlabel;
    vm.deletelabel = deletelabel;
    vm.add = false;
    vm.removeByValue = removeByValue;
    vm.selectclose = selectclose;
    vm.likeparam = null;
    vm.setlike = setlike;

    vm.user = JSON.parse($cookies.get("userInfo"));

    console.log("cook",vm.user);
    function setlike(like) {
        vm.likeparam = like;

    }

    function removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }


    vm.like = vm.user.usercollect.split(",");

    console.log(vm.like.length);
    vm.select = [
           "幽静唯美",
           "花中萌物",
           "奇花异草",
           "网友随拍",
           "植物与人",
           "求鉴定" ,
]

    function selectclose() {
        vm.add = false;
    }

    function addlabel() {
        if (vm.like.length >= 5) {
            alert("标签不能大于5个！");
            return;
        }
        vm.edit = true;
        vm.add = true;
    }

    function save() {
        vm.edit = false;

        for (var i = 0; i < vm.like.length; i++)
        {
            if(i==0){
                vm.user.usercollect= vm.like[0]
            }else{
                vm.user.usercollect = vm.user.usercollect + "," + vm.like[i]
            }


        }
        AutherService.updateUser(vm.user).$promise.then(function (data) {
            $cookies.put("userInfo", JSON.stringify(vm.user), {'expires': new Date(new Date().getTime() + 24 * 3600 * 1000)});

            request = data;
            console.log(request)

                       return alert("保存成功");
        }, function (err) {
            console.log(err);
            return alert(err.data.msg);
        });
    }

    function selectlabel(check) {
        if (vm.like.indexOf(check) >= 0) {
            vm.add = false;
        } else {
            vm.like.push(check);
            vm.add = false;
        }

    }

    function deletelabel(likeparam) {
        vm.removeByValue(vm.like, likeparam);
        vm.edit = true;
    }


}